import 'dart:io';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:convert';

class RequestForm extends StatelessWidget {
  final TextEditingController appKeyController = TextEditingController(text: 'mh_83c9393fcfd7b889');
  final TextEditingController timestampController = TextEditingController();
  final TextEditingController vController = TextEditingController(text: '1.0');
  final TextEditingController signMethodController = TextEditingController(text: 'MD5');
  final TextEditingController signController = TextEditingController(text: '123456');
  final TextEditingController imagePathController = TextEditingController(text: '/sdcard/Pictures/.thumbnails/11.jpg');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('公共上传文件'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              controller: appKeyController,
              decoration: InputDecoration(hintText: 'mh_83c9393fcfd7b889'),
            ),
            TextField(
              controller: vController,
              decoration: InputDecoration(hintText: '1.0'),
            ),
            TextField(
              controller: signMethodController,
              decoration: InputDecoration(hintText: 'MD5'),
            ),
            TextField(
              controller: signController,
              decoration: InputDecoration(hintText: '123456'),
            ),
            TextField(
              controller: imagePathController,
              decoration: InputDecoration(hintText: '请输入图像路径'),
            ),

            ElevatedButton(
              child: Text('上传'),
              onPressed: () async {
                if (appKeyController.text.isEmpty ||
                    vController.text.isEmpty ||
                    signMethodController.text.isEmpty ||
                    signController.text.isEmpty ||
                    imagePathController.text.isEmpty) {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('错误'),
                        content: Text('请填写所有必要的信息。'),
                        actions: <Widget>[
                          TextButton(
                            child: Text('确定'),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                        ],
                      );
                    },
                  );
                  return;
                }

                PermissionStatus status = await Permission.storage.request();

                if (await Permission.manageExternalStorage.request().isGranted) {
                  // 创建一个 File 对象
                  File imageFile = File(imagePathController.text);

                  // 读取文件内容作为字节列表
                  Uint8List bytes = await imageFile.readAsBytes();

                  var request = http.MultipartRequest('POST', Uri.parse('https://cbec-studapi.gzport.net/api/index/upload'));

                  request.fields['app_key'] = appKeyController.text;
                  request.fields['timestamp'] = DateTime.now().millisecondsSinceEpoch.toString();;
                  request.fields['v'] = vController.text;
                  request.fields['sign_method'] = signMethodController.text;
                  request.fields['sign'] = signController.text;

                  request.files.add(http.MultipartFile.fromBytes('file', bytes, filename: 'image.jpg'));

                  var response = await request.send();

                  http.Response res = await http.Response.fromStream(response);

                  if (res.statusCode == 200) {
                    print("上传成功");
                    Map<String, dynamic> responseData = jsonDecode(res.body);
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('上传成功'),
                          content: SingleChildScrollView(
                            child: ListBody(
                              children: <Widget>[
                                Text('响应状态: ${responseData['status']}'),
                                Text('响应代码: ${responseData['code']}'),
                                Text('响应信息: ${responseData['message']}'),
                                Text('响应时间: ${responseData['time']}'),
                                Text('企业用户id: ${responseData['app_key']}'),
                                Text('签名算法: ${responseData['sign_method']}'),
                                Text('加密信息: ${responseData['sign']}'),
                                Text('响应数据: ${responseData['data']}'),
                              ],
                            ),
                          ),
                          actions: <Widget>[
                            TextButton(
                              child: Text('确定'),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      },
                    );
                  } else {
                    print("上传失败");
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('上传失败'),
                          content: SingleChildScrollView(
                            child: ListBody(
                              children: <Widget>[
                                Text('响应状态: ${res.statusCode}'),
                                Text('响应信息: ${res.reasonPhrase}'),
                              ],
                            ),
                          ),
                          actions: <Widget>[
                            TextButton(
                              child: Text('确定'),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      },
                    );
                  }
                } else {
                  print("存储权限未被授予");
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}